package com.ruoyi.filemanager.command;

import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.filemanager.constant.ElFinderConstants;
import com.ruoyi.filemanager.service.ElfinderStorage;
import com.ruoyi.filemanager.service.VolumeHandler;
import com.ruoyi.filemanager.util.ImageUtil;

public class PutCommand extends AbstractJsonCommand implements ElfinderCommand
{
    public static final String ENCODING = Constants.UTF8;
    public static final String IMAGE_BASE64_FLAG = ";base64,";

    @Override
    protected void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, JSONObject json)
            throws Exception
    {
        final String target = request.getParameter(ElFinderConstants.ELFINDER_PARAMETER_TARGET);
        VolumeHandler file = findTarget(elfinderStorage, target);
        OutputStream os = file.openOutputStream();
        String content = request.getParameter(ElFinderConstants.ELFINDER_PARAMETER_CONTENT);
        if (content.contains(IMAGE_BASE64_FLAG))
        {
            byte[] bytes = ImageUtil
                    .base64ToImg(content.substring(content.indexOf(IMAGE_BASE64_FLAG) + IMAGE_BASE64_FLAG.length()));
            IOUtils.write(bytes, os);
        }
        else
        {
            IOUtils.write(content, os, ENCODING);
        }
        os.close();
        json.put(ElFinderConstants.ELFINDER_JSON_RESPONSE_CHANGED, new Object[] { getTargetInfo(request, file) });
    }
}
